package fr.alesia.deepstack.data.jdo;

import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.jdo.Extent;

import fr.alesia.deepstack.bean.Tournament;
import fr.alesia.deepstack.bean.jdo.TournamentJdo;
import fr.alesia.deepstack.data.DataAccessObject;
import fr.alesia.deepstack.data.TournamentDao;

public class TournamentDaoJdo extends AbstractDao implements DataAccessObject, TournamentDao {

	private static TournamentDao instance = null;
	
	private TournamentDaoJdo(){}
	
	public static TournamentDao getInstance(){
		if(instance == null){		
			instance = new TournamentDaoJdo();
		}
		return instance;
	}

	public void delete(Tournament tournament) {
		
		open();
		Tournament base = manager.getObjectById(TournamentJdo.class, tournament.getId());
		manager.deletePersistent(base);
		close();
	}

	public Tournament find(String id) {
		
		open();
		Tournament tournament = manager.getObjectById(TournamentJdo.class, id);
		close();
		return tournament;
	}

	public SortedSet<Tournament> findAll() {
		
		open();
		Set<Tournament> tournaments = new HashSet<Tournament>(50);
	    Extent<TournamentJdo> extent = manager.getExtent(TournamentJdo.class);
	    for (TournamentJdo tournament : extent) {
	    	tournaments.add(tournament);
	    }
	    extent.closeAll();
	    close();
		extent = null;
		return new TreeSet<Tournament>(tournaments);
	}

	public void insert(Tournament tournament) {
		
		tournament.setId((tournament.getId() == null ? "k" + tournament.hashCode() : tournament.getId()));
		open();
		manager.makePersistent(tournament);
		close();
	}

	public void update(Tournament tournament) {

		open();
		Tournament base = manager.getObjectById(TournamentJdo.class, tournament.getId());
		base.setDate(tournament.getDate());
		manager.makePersistent(base);
		close();
	}
}
